package com.rxt.thermopro.app

import android.annotation.SuppressLint
import android.database.Cursor
import android.media.RingtoneManager
import android.net.Uri
import com.orhanobut.hawk.Hawk
import com.rxt.thermopro.R
import com.rxt.thermopro.bean.*
import com.rxt.thermopro.ex.is24HourStyle
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.Executors


class LocalDataDao private constructor() {

    companion object {
        val INSTANCE: LocalDataDao by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            LocalDataDao()
        }

        const val TEMP_UNIT_C = "°C"
        const val TEMP_UNIT_F = "°F"

    }

    init {
        val list = mutableListOf<ProfileBean>()
        val defaultList = Hawk.get<MutableList<ProfileBean>>("profileDefaultList", mutableListOf())
        if (defaultList.isEmpty()) {
            val itemBean = ProfileItem(
                "Rare", "52",
                true
            )
            val itemBean1 = ProfileItem(
                "Medium Rare",
                "60"
            )
            val itemBean2 = ProfileItem(
                "Medium",
                "66"
            )
            val itemBean3 = ProfileItem(
                "Medium Well",
                "71"
            )
            val itemBean4 = ProfileItem(
                "Well Done",
                "77"
            )
            val itemList = mutableListOf<ProfileItem>()
            itemList.add(itemBean)
            itemList.add(itemBean1)
            itemList.add(itemBean2)
            itemList.add(itemBean3)
            itemList.add(itemBean4)

            val bean = ProfileBean(
                "Beef",
                "Medium Rare " + "60",
                itemList,
                "60",
                iconRes = R.drawable.meat1
            )
            val bean1 = ProfileBean(
                "Fish",
                "63",
                mutableListOf(),
                "63",
                iconRes = R.drawable.meat2
            )
            val bean2 =
                ProfileBean(
                    "Ground Beef",
                    "71",
                    mutableListOf(),
                    "71",
                    iconRes = R.drawable.meat3
                )
            val bean3 =
                ProfileBean(
                    "Ground Poultry",
                    "80",
                    mutableListOf(),
                    "80",
                    iconRes = R.drawable.meat4
                )

            val itemList1 = mutableListOf<ProfileItem>()
            itemList1.add(ProfileItem("Rare", "60"))
            itemList1.add(ProfileItem("Medium Rare", "63"))
            itemList1.add(ProfileItem("Medium", "71", true))
            itemList1.add(ProfileItem("Medium Well", "74"))
            itemList1.add(ProfileItem("Well Done", "77"))
            val bean4 = ProfileBean(
                "Lamb",
                "Medium " + "71",
                itemList1,
                "71",
                iconRes = R.drawable.meat5
            )

            val itemList2 = mutableListOf<ProfileItem>()
            itemList2.add(ProfileItem("Medium", "71"))
            itemList2.add(ProfileItem("Medium Well", "74", true))
            itemList2.add(ProfileItem("Well Done", "77"))
            val bean5 =
                ProfileBean(
                    "Pork",
                    "Medium Well " + "74",
                    itemList2,
                    "74",
                    iconRes = R.drawable.meat6
                )

            val bean6 = ProfileBean(
                "Poultry",
                "74",
                mutableListOf(),
                "74",
                iconRes = R.drawable.meat7
            )

            val bean7 = ProfileBean(
                "Turkey",
                "74",
                mutableListOf(),
                "74",
                iconRes = R.drawable.meat8
            )

            val itemList3 = mutableListOf<ProfileItem>()
            itemList3.add(
                ProfileItem(
                    "Rare",
                    "52",
                    true
                )
            )
            itemList3.add(
                ProfileItem(
                    "Medium Rare",
                    "60"
                )
            )
            itemList3.add(
                ProfileItem(
                    "Medium",
                    "66"
                )
            )
            itemList3.add(
                ProfileItem(
                    "Medium Well",
                    "71"
                )
            )
            itemList3.add(
                ProfileItem(
                    "Well Done",
                    "74"
                )
            )
            val bean8 = ProfileBean(
                "Veal",
                "Rare " + "52",
                itemList3,
                "52",
                iconRes = R.drawable.meat10
            )
            bean.id = "0"
            list.add(bean)
            bean1.id = "1"
            list.add(bean1)
            bean2.id = "2"
            list.add(bean2)
            bean3.id = "3"
            list.add(bean3)
            bean4.id = "4"
            list.add(bean4)
            bean5.id = "5"
            list.add(bean5)
            bean6.id = "6"
            list.add(bean6)
            bean7.id = "7"
            list.add(bean7)
            bean8.id = "8"
            list.add(bean8)
            Hawk.put("profileDefaultList", list)
            Hawk.put("profileList", list)
        }
    }


    fun getDeviceList(): MutableList<DeviceBean> {
        return Hawk.get<MutableList<DeviceBean>>("deviceList", mutableListOf())
    }

    fun saveDevice(bean: DeviceBean) {
        val list = Hawk.get<MutableList<DeviceBean>>("deviceList", mutableListOf())
        var hasAdd = false
        if (list.isNotEmpty()) {
            list.forEach {
                if (bean.address == it.address) {
                    hasAdd = true
                }
            }
        }
        if (!hasAdd) {
            list.add(bean)
        }
        Hawk.put("deviceList", list)
    }

    fun removeDevice(item: DeviceBean) {
        val list = Hawk.get<MutableList<DeviceBean>>("deviceList", mutableListOf())
        if (list.isNotEmpty()) {
            val iterator = list.iterator()
            while (iterator.hasNext()) {
                val it = iterator.next()
                if (it.address == item.address) {
                    iterator.remove()
                }
            }
        }
        Hawk.put("deviceList", list)
    }

    fun removeDevice(address: String) {
        val list = Hawk.get<MutableList<DeviceBean>>("deviceList", mutableListOf())
        if (list.isNotEmpty()) {
            val iterator = list.iterator()
            while (iterator.hasNext()) {
                val it = iterator.next()
                if (it.address == address) {
                    iterator.remove()
                }
            }
        }
        Hawk.put("deviceList", list)
    }


    fun getDefaultProfileList(): MutableList<ProfileBean> {
        return Hawk.get<MutableList<ProfileBean>>("profileDefaultList", mutableListOf())
    }

    fun getCurrentProfileList(): MutableList<ProfileBean> {
        val list = Hawk.get<MutableList<ProfileBean>>("profileList", mutableListOf())
        return if (list.isEmpty()) {
            val defaultList =
                Hawk.get<MutableList<ProfileBean>>("profileDefaultList", mutableListOf())
            Hawk.put("profileList", defaultList)
            defaultList
        } else {
            list
        }
    }

    fun addProfile(bean: ProfileBean) {
        val list = Hawk.get<MutableList<ProfileBean>>("profileList", mutableListOf())
        bean.id = (list.last().id.toInt() + 1).toString()
        list.add(bean)
        Hawk.put("profileList", list)
    }

    fun deleteProfile(bean: ProfileBean) {
        val list = Hawk.get<MutableList<ProfileBean>>("profileList", mutableListOf())
        val iterator = list.iterator()
        while (iterator.hasNext()) {
            val nextBean = iterator.next()
            if (nextBean.id == bean.id) {
                iterator.remove()
            }
        }
        Hawk.put("profileList", list)
    }

    fun resetProfile() {
        Hawk.delete("profileList")
    }

    fun updateProfile(bean: ProfileBean) {
        val list = Hawk.get<MutableList<ProfileBean>>("profileList", mutableListOf())
        val iterator = list.iterator()
        while (iterator.hasNext()) {
            val nextBean = iterator.next()
            if (nextBean.id == bean.id && nextBean.name == bean.name) {
                nextBean.highTemperatureNum = bean.highTemperatureNum
                nextBean.lowTemperatureNum = bean.lowTemperatureNum

                nextBean.highValueF = bean.highValueF
                nextBean.lowValueF = bean.lowValueF
                nextBean.highValueC = bean.highValueC
                nextBean.lowValueC = bean.lowValueC

                nextBean.itemValues = bean.itemValues
                if (nextBean.itemValues.isNotEmpty()) {
                    nextBean.itemValues.forEach {
                        if (it.checked) {
                            nextBean.highTemperatureNum = it.itemValue
                        }
                    }
                }
                nextBean.checked = bean.checked
                nextBean.profileValue = bean.profileValue
            }
        }
        Hawk.put("profileList", list)
    }

//    fun updateProfile(bean: ProfileBean) {
//        val list = Hawk.get<MutableList<ProfileBean>>("profileList", mutableListOf())
//        val iterator = list.iterator()
//        while (iterator.hasNext()) {
//            val nextBean = iterator.next()
//            if (nextBean.id == bean.id  && nextBean.name==bean.name) {
//                if (getTempUnit() == TEMP_UNIT_C) {
//                    nextBean.highTemperatureNum = bean.highTemperatureNum
//                    nextBean.lowTemperatureNum = bean.lowTemperatureNum
//
//                    nextBean.highValueF = transUnitCToF(bean.highTemperatureNum)
//                    nextBean.lowValueF = transUnitCToF(bean.lowTemperatureNum)
//                } else {
//                    nextBean.highTemperatureNum = transUnitFToC(bean.highValueF)
//                    nextBean.lowTemperatureNum = transUnitFToC(bean.lowValueF)
//                    nextBean.highValueF = bean.highValueF
//                    nextBean.lowValueF = bean.lowValueF
//                }
//
//                nextBean.itemValues = bean.itemValues
//                nextBean.checked = bean.checked
//                if (bean.itemValues.isEmpty()) {
//                    if (bean.singleTemp) {
//                        nextBean.profileValue = nextBean.highTemperatureNum
//                    } else {
//                        nextBean.profileValue =
//                            nextBean.lowTemperatureNum + "~" + nextBean.highTemperatureNum
//                    }
//                } else {
//                    nextBean.itemValues.forEach {
//                        if (getTempUnit() == TEMP_UNIT_F) {
//                            it.itemValue = transUnitFToC(it.itemValueF)
//                        } else {
//                            it.itemValueF = transUnitCToF(it.itemValue)
//                        }
//                        if (it.checked) {
//                            if (getTempUnit() == TEMP_UNIT_C) {
//                                nextBean.profileValue = it.itemName + " " + it.itemValue
//                            } else {
//                                nextBean.profileValue = it.itemName + " " + it.itemValueF
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        Hawk.put("profileList", list)
//    }


    fun getDefaultProfile(bean: ProfileBean): ProfileBean {
        val defaultList = Hawk.get<MutableList<ProfileBean>>("profileDefaultList", mutableListOf())
        val iterator = defaultList.iterator()
        while (iterator.hasNext()) {
            val nextBean = iterator.next()
            if (nextBean.id == bean.id) {
                bean.highTemperatureNum = nextBean.highTemperatureNum
                bean.lowTemperatureNum = nextBean.lowTemperatureNum
                bean.itemValues = nextBean.itemValues
                bean.profileValue = nextBean.profileValue
            }
        }
        return bean
    }

    val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm")

    private val threadPool = Executors.newFixedThreadPool(3)
    private var saveWorking = false

    //每根探针历史记录
    val cacheProbeHistory =
        Collections.synchronizedMap(hashMapOf<String, MutableList<ProbeHistoryBean>>())

    //探针历史记录最新一条索引
    private val cacheLastProbeHistoryIndex = Collections.synchronizedMap(hashMapOf<String, Int>())

    //获取探针所有历史记录的索引
    private fun initSaveHistory(keyStr: String) {
        if (!cacheLastProbeHistoryIndex.containsKey(keyStr)) {
            val indexList = Hawk.get("${keyStr}_history", mutableListOf<Int>())
            val historyIndex = if (indexList.isEmpty()) 0 else indexList.last() + 1
            cacheLastProbeHistoryIndex[keyStr] = historyIndex
            indexList.add(historyIndex)
            Hawk.put("${keyStr}_history", indexList)
        }
    }

    //获取探针所有历史记录
    fun getProbeHistoryList(address: String, probeIndex: Int): MutableList<ProbeHistoryWrapper> {
        val keyStr = "${address}_${probeIndex}"
        val indexList = Hawk.get("${keyStr}_history", mutableListOf<Int>())
        val historyList = mutableListOf<ProbeHistoryWrapper>()
        if (indexList.isNotEmpty()) {
            for (i in 0 until indexList.size) {
                val itemList =
                    Hawk.get("${keyStr}_history_${indexList[i]}", mutableListOf<ProbeHistoryBean>())
                if (itemList.isNotEmpty()) {
                    val lastBean = itemList.last()
                    val itemBean = ProbeHistoryWrapper(
                        lastBean.probeIndex,
                        lastBean.profile,
                        lastBean.tempTime,
                        itemList
                    )
                    historyList.add(itemBean)
                }
            }
        }
        return historyList
    }

    /**
     * 删除指定历史记录
     */
    fun deleteHistory(item: ProbeHistoryWrapper) {
        val address = item.itemList.last().address
        val probeIndex = item.probeIndex
        val historyIndex = item.itemList.last().historyIndex
        Hawk.delete("${address}_${probeIndex}_history_${historyIndex}")
    }


    fun getProbeHistoryListByIndex(
        address: String,
        probeIndex: Int,
        index: Int
    ): ProbeHistoryWrapper {
        val keyStr = "${address}_${probeIndex}"
        val itemList =
            Hawk.get("${keyStr}_history_${index}", mutableListOf<ProbeHistoryBean>())
        if (itemList.isNotEmpty()) {
            val lastBean = itemList.last()
            return ProbeHistoryWrapper(
                lastBean.probeIndex,
                lastBean.profile,
                lastBean.tempTime,
                itemList
            )
        }
        return ProbeHistoryWrapper(
            -1,
            LocalDataDao.INSTANCE.getProfile1(address),
            "",
            itemList
        )
    }

    val lock = Object()

    /**
     * 开启存储历史记录到本地
     */
    fun startSaveHistory() {
        saveWorking = true
        threadPool.execute {
            while (saveWorking) {
                if (cacheProbeHistory.isNotEmpty()) {
                    cacheProbeHistory.keys.forEach { keyStr ->
                        synchronized(lock) {
                            try {
                                initSaveHistory(keyStr)
                                //存储探针温度到本地历史记录
                                val historyIndex = cacheLastProbeHistoryIndex[keyStr] ?: -1
                                cacheProbeHistory[keyStr]?.forEach {
                                    it.historyIndex = historyIndex
                                }
                                Hawk.put(
                                    "${keyStr}_history_${historyIndex}",
                                    cacheProbeHistory[keyStr]
                                )
                                println("---> startSaveHistory saveWorking====$saveWorking  historyIndex=$historyIndex")
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                }
                Thread.sleep(10000)
            }
        }
    }

    /**
     * 停止存储历史记录到本地
     */
    fun stopSaveHistory() {
        saveWorking = false
//        threadPool.shutdown()
    }

    //    val cacheHistoryTemp = mutableListOf<TempBean>()
    val cacheHistoryTemp = hashMapOf<String, MutableList<TempBean>>()


    fun getHistoryTempData(address: String): MutableList<TempBean> {
        val list = mutableListOf<TempBean>()
        val currentMillis = System.currentTimeMillis()
        val tempBean = TempBean()
        tempBean.tempTime = currentMillis.toString()
        tempBean.tempNum1 = "0"
        tempBean.tempNum2 = "0"
        tempBean.tempNum3 = "0"
        tempBean.tempNum4 = "0"
        list.add(tempBean)

//        val currentMillis = System.currentTimeMillis()
//        for (i in 0 until 20) {
//            val tempBean = TempBean()
//            tempBean.tempTime = (currentMillis + i * 1000 * 60).toString()
//            tempBean.tempNum1 = (Math.random() * 80 + i).toInt().toString()
//            tempBean.tempNum2 = (Math.random() * 80 + i).toInt().toString()
//            tempBean.tempNum3 = (Math.random() * 80 + i).toInt().toString()
//            tempBean.tempNum4 = (Math.random() * 80 + i).toInt().toString()
//            list.add(tempBean)
//            val date = Date()
//            date.time = tempBean.tempTime.toLong()
//            val timeStr = dateFormat.format(date)
//            println("=======>getHistoryTempData time=$i --$timeStr  timeMillis=${tempBean.tempTime}  tempNum1=${tempBean.tempNum1}")
//        }
//        println("=======>getHistoryTempData=$list")
        if (cacheHistoryTemp.containsKey(address)) {
            cacheHistoryTemp.remove(address)
        }
        cacheHistoryTemp[address] = list
        return list
    }

    @JvmName("getCacheHistoryTemp1")
    fun getCacheHistoryTemp(address: String): MutableList<TempBean> {
        return cacheHistoryTemp[address] ?: mutableListOf()
    }

    fun saveProfile1(bean: ProfileBean) {
        Hawk.put("profileBean1", bean)
    }

    fun saveProfile1(bean: ProfileBean, address: String) {
        Hawk.put("profileBean1_$address", bean)
    }

    fun saveProfile2(bean: ProfileBean, address: String) {
        Hawk.put("profileBean2_$address", bean)
    }

    fun saveProfile3(bean: ProfileBean, address: String) {
        Hawk.put("profileBean3_$address", bean)
    }

    fun saveProfile4(bean: ProfileBean, address: String) {
        Hawk.put("profileBean4_$address", bean)
    }

    fun saveProfileHeader(bean: ProfileBean) {
        Hawk.put("profileHeader", bean)
    }

    fun updateProfileHeader(highValue: String, lowValue: String) {
        val bean = Hawk.get<ProfileBean>(
            "profileHeader", ProfileBean(
                "Ambient Temperature",
                "",
                mutableListOf(),
                "250",
                "50",
                highValueF = "482",
                lowValueF = "122",
                singleTemp = false,
                iconRes = R.drawable.main_ic0
            )
        )
        if (getTempUnit() == TEMP_UNIT_C) {
            bean.highTemperatureNum = highValue
            bean.lowTemperatureNum = lowValue

            bean.highValueF = transUnitCToF(highValue)
            bean.lowValueF = transUnitCToF(lowValue)
        } else {
            bean.highValueF = highValue
            bean.lowValueF = lowValue

            bean.highTemperatureNum = transUnitFToC(highValue)
            bean.lowTemperatureNum = transUnitFToC(lowValue)
        }
        Hawk.put("profileHeader", bean)
    }

    fun getProfileHeader(): ProfileBean {
        return Hawk.get<ProfileBean>(
            "profileHeader", ProfileBean(
                "Ambient Temperature",
                "",
                mutableListOf(),
                "250",
                "50",
                highValueF = "482",
                lowValueF = "122",
                singleTemp = false,
                iconRes = R.drawable.main_ic0
            )
        )
    }

    fun hasNeedSetProbeProfile(address: String, mPosition: Int): Boolean {
        var hasNeed = false
        val list = getCurrentProfileList()
        when (mPosition) {
            1 -> {
                val filter1 = list.filter { getProfile1(address).name == it.name }
                if (filter1.isEmpty()) {
                    Hawk.delete("profileBean1_$address")
                    hasNeed = true
                } else {
                    val newItem = filter1.first()
                    val oldItem = getProfile1(address)
                    if (newItem.highTemperatureNum != oldItem.highTemperatureNum ||
                        newItem.lowTemperatureNum != oldItem.lowTemperatureNum
                    ) {
                        saveProfile1(newItem, address)
                        hasNeed = true
                    }
                    if (oldItem.itemValues.isNotEmpty()) {
                        for (i in oldItem.itemValues.indices) {
                            if (oldItem.itemValues[i].itemValue != newItem.itemValues[i].itemValue) {
                                saveProfile1(newItem, address)
                                hasNeed = true
                                break
                            }
                        }
                    }
                }
            }
            2 -> {
                val filter2 = list.filter { getProfile2(address).name == it.name }
                if (filter2.isEmpty()) {
                    Hawk.delete("profileBean2_$address")
                    hasNeed = true
                } else {
                    val newItem = filter2.first()
                    val oldItem = getProfile2(address)
                    if (newItem.highTemperatureNum != oldItem.highTemperatureNum ||
                        newItem.lowTemperatureNum != oldItem.lowTemperatureNum
                    ) {
                        saveProfile2(newItem, address)
                        hasNeed = true
                    }
                    if (oldItem.itemValues.isNotEmpty()) {
                        for (i in oldItem.itemValues.indices) {
                            if (oldItem.itemValues[i].itemValue != newItem.itemValues[i].itemValue) {
                                saveProfile2(newItem, address)
                                hasNeed = true
                                break
                            }
                        }
                    }
                }
            }
            3 -> {
                val filter3 = list.filter { getProfile3(address).name == it.name }
                if (filter3.isEmpty()) {
                    Hawk.delete("profileBean3_$address")
                    hasNeed = true
                } else {
                    val newItem = filter3.first()
                    val oldItem = getProfile3(address)
                    if (newItem.highTemperatureNum != oldItem.highTemperatureNum ||
                        newItem.lowTemperatureNum != oldItem.lowTemperatureNum
                    ) {
                        saveProfile3(newItem, address)
                        hasNeed = true
                    }
                    if (oldItem.itemValues.isNotEmpty()) {
                        for (i in oldItem.itemValues.indices) {
                            if (oldItem.itemValues[i].itemValue != newItem.itemValues[i].itemValue) {
                                saveProfile3(newItem, address)
                                hasNeed = true
                                break
                            }
                        }
                    }
                }
            }
            4 -> {
                val filter4 = list.filter { getProfile4(address).name == it.name }
                if (filter4.isEmpty()) {
                    Hawk.delete("profileBean4_$address")
                    hasNeed = true
                } else {
                    val newItem = filter4.first()
                    val oldItem = getProfile4(address)
                    if (newItem.highTemperatureNum != oldItem.highTemperatureNum ||
                        newItem.lowTemperatureNum != oldItem.lowTemperatureNum
                    ) {
                        saveProfile4(newItem, address)
                        hasNeed = true
                    }
                    if (oldItem.itemValues.isNotEmpty()) {
                        for (i in oldItem.itemValues.indices) {
                            if (oldItem.itemValues[i].itemValue != newItem.itemValues[i].itemValue) {
                                saveProfile4(newItem, address)
                                hasNeed = true
                                break
                            }
                        }
                    }
                }
            }
        }
        return hasNeed
    }

    fun getProfile1(): ProfileBean {
        return Hawk.get(
            "profileBean1", ProfileBean(
                "MEAT",
                "", mutableListOf(), singleTemp = false
            )
        )
    }


    fun getProfile2(): ProfileBean {
        return Hawk.get(
            "profileBean2", ProfileBean(
                "MEAT",
                "", mutableListOf(), singleTemp = false
            )
        )
    }

    fun getProfile3(): ProfileBean {
        return Hawk.get(
            "profileBean3", ProfileBean(
                "MEAT",
                "", mutableListOf(), singleTemp = false
            )
        )
    }


    fun getProfile4(): ProfileBean {
        return Hawk.get(
            "profileBean4", ProfileBean(
                "MEAT",
                "", mutableListOf(), singleTemp = false
            )
        )
    }

    fun getProfile1(address: String): ProfileBean {
        return Hawk.get(
            "profileBean1_$address", ProfileBean(
                "MEAT",
                "", mutableListOf(), singleTemp = false
            )
        )
    }


    fun getProfile2(address: String): ProfileBean {
        return Hawk.get(
            "profileBean2_$address", ProfileBean(
                "MEAT",
                "", mutableListOf(), singleTemp = false
            )
        )
    }

    fun getProfile3(address: String): ProfileBean {
        return Hawk.get(
            "profileBean3_$address", ProfileBean(
                "MEAT",
                "", mutableListOf(), singleTemp = false
            )
        )
    }


    fun getProfile4(address: String): ProfileBean {
        return Hawk.get(
            "profileBean4_$address", ProfileBean(
                "MEAT",
                "", mutableListOf(), singleTemp = false
            )
        )
    }

    fun saveAlarmText1(alarmText: String, address: String) {
        Hawk.put("alarmText1_$address", alarmText)
    }

    fun saveAlarmText2(alarmText: String, address: String) {
        Hawk.put("alarmText2_$address", alarmText)
    }

    fun saveAlarmText3(alarmText: String, address: String) {
        Hawk.put("alarmText3_$address", alarmText)
    }

    fun saveAlarmText4(alarmText: String, address: String) {
        Hawk.put("alarmText4_$address", alarmText)
    }

    fun resetAlarmText1(address: String) {
        Hawk.put("alarmText1_$address", "")
    }

    fun resetAlarmText2(address: String) {
        Hawk.put("alarmText2_$address", "")
    }

    fun resetAlarmText3(address: String) {
        Hawk.put("alarmText3_$address", "")
    }

    fun resetAlarmText4(address: String) {
        Hawk.put("alarmText4_$address", "")
    }

    fun getAlarmText1(address: String): String {
        return Hawk.get("alarmText1_$address", "")
    }

    fun getAlarmText2(address: String): String {
        return Hawk.get("alarmText2_$address", "")
    }

    fun getAlarmText3(address: String): String {
        return Hawk.get("alarmText3_$address", "")
    }

    fun getAlarmText4(address: String): String {
        return Hawk.get("alarmText4_$address", "")
    }

    fun setTempUnit(tempUnit: String) {
        Hawk.put("tempUnit", tempUnit)
    }

    fun getTempUnit(): String {
        return Hawk.get("tempUnit", TEMP_UNIT_C)
    }

    fun convertUnit(numStr: String): String {
        return when {
            numStr.isEmpty() -> {
                ""
            }
            getTempUnit() == TEMP_UNIT_C -> {
                numStr + TEMP_UNIT_C
            }
            else -> {
                BigDecimal(32 + numStr.toInt() * 1.8).setScale(0, RoundingMode.DOWN)
                    .toString() + TEMP_UNIT_F
            }
        }
    }

    fun convertUnitNum(numStr: String): String {
        return when {
            getTempUnit() == TEMP_UNIT_C -> {
                numStr
            }
            numStr.isEmpty() -> {
                ""
            }
            else -> {
                32 + numStr.toInt() * 1.8
                BigDecimal(32 + numStr.toInt() * 1.8).setScale(0, RoundingMode.DOWN).toString()
            }
        }
    }

    fun transUnitFToC(numStr: String): String {
        return if (numStr.isEmpty()) {
            ""
        } else {
            BigDecimal((numStr.toInt() - 32) / 1.8).setScale(0, RoundingMode.DOWN)
                .toString()
        }
    }

    fun transFloatUnitFToC(numStr: String): String {
        return if (numStr.isEmpty()) {
            ""
        } else {
            BigDecimal((numStr.toFloat() - 32) / 1.8).setScale(1, RoundingMode.DOWN)
                .toString()
        }
    }

    fun transUnitCToF(numStr: String): String {
        return if (numStr.isEmpty()) {
            ""
        } else {
            BigDecimal(32 + numStr.toInt() * 1.8).setScale(0, RoundingMode.DOWN)
                .toString()
        }
    }

    fun transFloatUnitCToF(numStr: String): String {
        return if (numStr.isEmpty()) {
            ""
        } else {
            BigDecimal(32 + numStr.toFloat() * 1.8).setScale(1, RoundingMode.DOWN)
                .toString()
        }
    }

    fun formatHighValueUnit(mProfileBean: ProfileBean): String {
        return if (getTempUnit() == TEMP_UNIT_F) {
            if (mProfileBean.highValueF.isEmpty()
            ) {
                transUnitCToF(mProfileBean.highTemperatureNum) + TEMP_UNIT_F
            } else {
                mProfileBean.highValueF + TEMP_UNIT_F
            }
        } else {
            mProfileBean.highTemperatureNum + TEMP_UNIT_C
        }
    }

    fun formatHighValueUnitNum(mProfileBean: ProfileBean): String {
        return if (getTempUnit() == TEMP_UNIT_F) {
            if (mProfileBean.highValueF.isEmpty()
            ) {
                transUnitCToF(mProfileBean.highTemperatureNum)
            } else {
                mProfileBean.highValueF
            }
        } else {
            mProfileBean.highTemperatureNum
        }
    }

    fun formatLowValueUnit(mProfileBean: ProfileBean): String {
        return if (getTempUnit() == TEMP_UNIT_F) {
            if (mProfileBean.lowValueF.isEmpty()
            ) {
                transUnitCToF(mProfileBean.lowTemperatureNum) + TEMP_UNIT_F
            } else {
                mProfileBean.lowValueF + TEMP_UNIT_F
            }
        } else {
            mProfileBean.lowTemperatureNum + TEMP_UNIT_C
        }
    }

    fun formatLowValueUntNum(mProfileBean: ProfileBean): String {
        return if (getTempUnit() == TEMP_UNIT_F) {
            if (mProfileBean.lowValueF.isEmpty()
            ) {
                transUnitCToF(mProfileBean.lowTemperatureNum)
            } else {
                mProfileBean.lowValueF
            }
        } else {
            mProfileBean.lowTemperatureNum
        }
    }

    fun setDisconnectNotice(isNotice: Boolean) {
        Hawk.put("disconnectNotice", isNotice)
    }

    fun isDisconnectNotice(): Boolean {
        return Hawk.get("disconnectNotice", true)
    }

    fun setAlarm(isAlarm: Boolean) {
        Hawk.put("isAlarm", isAlarm)
    }

    fun isAlarm(): Boolean {
        return Hawk.get("isAlarm", true)
    }

    fun setDisconnectNotice(isNotice: Boolean, address: String) {
        Hawk.put("disconnectNotice_$address", isNotice)
    }

    fun isDisconnectNotice(address: String): Boolean {
        return Hawk.get("disconnectNotice_$address", true)
    }

    fun setAlarm(isAlarm: Boolean, address: String) {
        Hawk.put("isAlarm_$address", isAlarm)
    }

    fun isAlarm(address: String): Boolean {
        return Hawk.get("isAlarm_$address", true)
    }

    fun setProbeAlarm1(index: Int, address: String) {
        Hawk.put("probeAlarm1_$address", index)
    }

    fun getProbeAlarm1(address: String): Int {
        return Hawk.get("probeAlarm1_$address", 0)
    }

    fun setProbeAlarm2(index: Int, address: String) {
        Hawk.put("probeAlarm2_$address", index)
    }

    fun getProbeAlarm2(address: String): Int {
        return Hawk.get("probeAlarm2_$address", 0)
    }

    fun setProbeAlarm3(index: Int, address: String) {
        Hawk.put("probeAlarm3_$address", index)
    }

    fun getProbeAlarm3(address: String): Int {
        return Hawk.get("probeAlarm3_$address", 0)
    }

    fun setProbeAlarm4(index: Int, address: String) {
        Hawk.put("probeAlarm4_$address", index)
    }

    fun getProbeAlarm4(address: String): Int {
        return Hawk.get("probeAlarm4_$address", 0)
    }

    fun setProbeAlarm1(index: Int) {
        Hawk.put("probeAlarm1", index)
    }

    fun getProbeAlarm1(): Int {
        return Hawk.get("probeAlarm1", 0)
    }

    fun setProbeAlarm2(index: Int) {
        Hawk.put("probeAlarm2", index)
    }

    fun getProbeAlarm2(): Int {
        return Hawk.get("probeAlarm2", 0)
    }

    fun setProbeAlarm3(index: Int) {
        Hawk.put("probeAlarm3", index)
    }

    fun getProbeAlarm3(): Int {
        return Hawk.get("probeAlarm3", 0)
    }

    fun setProbeAlarm4(index: Int) {
        Hawk.put("probeAlarm4", index)
    }

    fun getProbeAlarm4(): Int {
        return Hawk.get("probeAlarm4", 0)
    }

    private val ringListCache = mutableListOf<RingBean>()
    fun getProbeAlarmList(): List<RingBean> {
        val list = ArrayList<String>()
        list.add("Default")
        list.add("Beat")
        list.add("Brave")
        list.add("Cartoon")
        list.add("Carve Our Names")
        list.add("Chilled")
        list.add("Classic Bell")
        list.add("Concentrate")
        list.add("Day lily")
        list.add("Day Ringtone")
        list.add("Dream")
        list.add("Dynamo")
        list.add("Eastern")
        list.add("Esports")
        list.add("Forest Day")
        list.add("Halo")
        list.add("Heart")
        list.add("Hello Ya")

        if (ringListCache.isEmpty()) {
            val ringtoneMgr = RingtoneManager(AppContext.get())
            ringtoneMgr.setType(RingtoneManager.TYPE_ALARM)
            val alarmsCursor: Cursor = ringtoneMgr.cursor
            val alarmsCount: Int = alarmsCursor.count
            if (alarmsCount == 0 && !alarmsCursor.moveToFirst()) {
                return emptyList()
            }
            val ringList = mutableListOf<RingBean>()
            ringList.add(RingBean("Default", Uri.parse(""), -1))
            while (!alarmsCursor.isAfterLast && alarmsCursor.moveToNext()) {
                val currentPosition = alarmsCursor.position
                val ringName =
                    ringtoneMgr.getRingtone(alarmsCursor.position).getTitle(AppContext.get())
                val ringUri = ringtoneMgr.getRingtoneUri(currentPosition)
                val bean = RingBean(ringName, ringUri, currentPosition)
                ringList.add(bean)
            }
            alarmsCursor.close()
            ringListCache.clear()
            ringListCache.addAll(ringList)
        }
        return ringListCache
    }

    fun setTempPreAlarm(index: Int) {
        Hawk.put("tempPreAlarm", index)
    }

    fun getTempPreAlarm(): Int {
        return Hawk.get("tempPreAlarm", 0)
    }

    fun setTempPreAlarm(index: Int, address: String) {
        Hawk.put("tempPreAlarm_$address", index)
    }

    fun getTempPreAlarm(address: String): Int {
        return Hawk.get("tempPreAlarm_$address", 0)
    }

    fun getTempPreAlarmList(): List<TempPreAlarmBean> {
        val list = ArrayList<TempPreAlarmBean>()
        list.add(TempPreAlarmBean("None", "None", "0"))
        list.add(TempPreAlarmBean("5° Before Set Temp", "5° Before", "5"))
        list.add(TempPreAlarmBean("10° Before Set Temp", "10° Before", "10"))
        list.add(TempPreAlarmBean("15° Before Set Temp", "15° Before", "15"))
        return list
    }

    fun setAlarmVibration(isAlarmVibration: Boolean) {
        Hawk.put("isAlarmVibration", isAlarmVibration)
    }

    fun isAlarmVibration(): Boolean {
        return Hawk.get("isAlarmVibration", true)
    }

    fun setAlarmVibration(isAlarmVibration: Boolean, address: String) {
        Hawk.put("isAlarmVibration_$address", isAlarmVibration)
    }

    fun isAlarmVibration(address: String): Boolean {
        return Hawk.get("isAlarmVibration_$address", true)
    }

    private val hasAlarmMap = hashMapOf<String, ProfileBean>()
    private val hasPreAlarmMap = hashMapOf<String, Int>()
    fun setHasAlarmProfile(
        probeIndex: Int,
        profileBean: ProfileBean,
        tempPreAlarmNum: Int,
        address: String
    ) {
        hasAlarmMap[probeIndex.toString() + "_" + address] = profileBean
        hasPreAlarmMap[probeIndex.toString() + "_" + address] = tempPreAlarmNum
    }

    fun removeAlarmProfile(probeIndex: Int, address: String) {
        if (hasAlarmMap.containsKey(probeIndex.toString() + "_" + address)) {
            hasAlarmMap.remove(probeIndex.toString() + "_" + address)
        }
        if (hasPreAlarmMap.containsKey(probeIndex.toString() + "_" + address)) {
            hasPreAlarmMap.remove(probeIndex.toString() + "_" + address)
        }
    }

    fun hasAlarmProfile(
        probeIndex: Int,
        profileBean: ProfileBean,
        tempPreAlarmNum: Int,
        address: String
    ): Boolean {
        return if (hasAlarmMap.keys.contains(probeIndex.toString() + "_" + address)) {
            hasAlarmMap[probeIndex.toString() + "_" + address]?.name == profileBean.name &&
                    hasAlarmMap[probeIndex.toString() + "_" + address]?.highTemperatureNum == profileBean.highTemperatureNum
                    &&
                    hasAlarmMap[probeIndex.toString() + "_" + address]?.lowTemperatureNum == profileBean.lowTemperatureNum
                    && hasPreAlarmMap[probeIndex.toString() + "_" + address] == tempPreAlarmNum
        } else {
            false
        }
    }

    private val hasResetProfileMap = hashMapOf<String, ProfileBean>()
    fun setNeedResetProfile(probeIndex: Int, profileBean: ProfileBean, address: String) {
        println("======> resetProfile   setNeedResetProfile probeIndex=$probeIndex  profileBean=$profileBean  ")
        hasResetProfileMap[probeIndex.toString() + "_" + address] = profileBean
    }

    fun removeResetProfile(probeIndex: Int, address: String) {
        if (hasResetProfileMap.containsKey(probeIndex.toString() + "_" + address)) {
            hasResetProfileMap.remove(probeIndex.toString() + "_" + address)
        }
    }

    fun hasNeedResetProfile(probeIndex: Int, profileBean: ProfileBean, address: String): Boolean {
        return if (hasResetProfileMap.keys.contains(probeIndex.toString() + "_" + address)) {
            hasResetProfileMap[probeIndex.toString() + "_" + address]?.name == profileBean.name &&
                    hasResetProfileMap[probeIndex.toString() + "_" + address]?.highTemperatureNum == profileBean.highTemperatureNum
                    &&
                    hasResetProfileMap[probeIndex.toString() + "_" + address]?.lowTemperatureNum == profileBean.lowTemperatureNum
        } else {
            false
        }
    }

    fun needGetLastHistory(address: String): Boolean {
        val nowTime = System.currentTimeMillis()
        val lastTime = Hawk.get("getHistoryTime_$address", 0L)
        return nowTime - lastTime > 10000
    }

    fun setGetHistoryTime(address: String) {
        val nowTime = System.currentTimeMillis()
        Hawk.put("getHistoryTime_$address", nowTime)
    }

    fun isTempAlarm359(address: String): Boolean {
        return Hawk.get("isTempAlarm359_$address", false)
    }

    fun setTempAlarm359(isOpen: Boolean, address: String) {
        println("======>  setTempAlarm359  $isOpen   $address")
        Hawk.put("isTempAlarm359_$address", isOpen)
    }

    fun isHumAlarm359(address: String): Boolean {
        return Hawk.get("isHumAlarm359_$address", false)
    }

    fun setHumAlarm359(isOpen: Boolean, address: String) {
        println("======>  setHumAlarm359  $isOpen   $address")
        Hawk.put("isHumAlarm359_$address", isOpen)
    }

    fun getTempProfile359(address: String): ProfileBean {
        return Hawk.get(
            "tempProfile359_$address", ProfileBean(
                "MEAT", "", mutableListOf(), highTemperatureNum = "60",
                lowTemperatureNum = "-20", singleTemp = false
            )
        )
    }

    fun setTempProfile359(address: String, bean: ProfileBean) {
        Hawk.put("tempProfile359_$address", bean)
    }

    fun getHumProfile359(address: String): ProfileBean {
        return Hawk.get(
            "humProfile359_$address", ProfileBean(
                "MEAT", "", mutableListOf(), highTemperatureNum = "99",
                lowTemperatureNum = "10", singleTemp = false
            )
        )
    }

    fun setHumProfile359(address: String, bean: ProfileBean) {
        Hawk.put("humProfile359_$address", bean)
    }

    fun clearSettingsByAddress(address: String) {
        Hawk.delete("profileBean1_$address")
        Hawk.delete("profileBean2_$address")
        Hawk.delete("profileBean3_$address")
        Hawk.delete("profileBean4_$address")

        Hawk.delete("alarmText1_$address")
        Hawk.delete("alarmText2_$address")
        Hawk.delete("alarmText3_$address")
        Hawk.delete("alarmText4_$address")

        Hawk.delete("getHistoryTime_$address")
    }

    fun formatNeedTime(needTime: String = ""): String {
        var newNeedTime = ""
        if (needTime.isEmpty()) {
            return "-- H:-- M:-- S"
        }
        val strList = needTime.split(":")
        when (strList.size) {
            0 -> {
                newNeedTime = "$needTime S"
            }
            1 -> {
                newNeedTime = "$needTime S"
            }
            2 -> {
                val s = strList[1]
                val m = strList[0].toInt()
                newNeedTime = if (m > 0) {
                    "$m M:$s S"
                } else {
                    "$s S"
                }
            }
            3 -> {
                val s = strList[2]
                val m = strList[1].toInt()
                val h = strList[0].toInt()
                newNeedTime = if (h > 0) {
                    "$h H:$m M:$s S"
                } else {
                    if (m > 0) {
                        "$m M:$s S"
                    } else {
                        "$s S"
                    }
                }
            }
        }
        return newNeedTime
    }

    private val DEFAULT_FORMAT_12_HOUR = "h:mm a"
    private val DEFAULT_FORMAT_24_HOUR = "kk:mm"
    private val dateFormat3 = SimpleDateFormat("dd-MM-yyyy HH:mm")
    private val dateFormat2 = SimpleDateFormat("yyyy-MM-dd-HH-mm")
    private val dateFormat1 = SimpleDateFormat("dd-MM-yyyy hh:mm")


    /**
     * AM 还是 PM
     */
    private fun getAMOrPM(date: Date, is24: Boolean): String {
        return if (!is24) {
            val str = dateFormat2.format(date)
            val str1 = str.split("-")[3]
            if (str1.toInt() > 12) {
                " PM"
            } else {
                " AM"
            }
        } else {
            ""
        }
    }

    fun formatTimeAMPM(dateTime: Long, is24: Boolean): String {
        val currentDateFormat = if (is24) {
            dateFormat3
        } else {
            dateFormat1
        }
        val date = Date()
        date.time = dateTime
        val timeStr = currentDateFormat.format(date)
        var newTimeStr=timeStr.split(" ")[1]
        if (!is24){
           if (newTimeStr.startsWith("0",true)){
               newTimeStr=newTimeStr.substring(1)
           }
        }
        val strTrip = getAMOrPM(date, is24)
        return newTimeStr + strTrip
    }

    @SuppressLint("SimpleDateFormat")
    fun formatDateTime(dateTime: Long): String {
        val date = Date()
        date.time = dateTime
        val sdf = SimpleDateFormat("MMMM d,yyyy")
        var formatDate = sdf.format(date)
        when {
            formatDate.contains("January", true) -> {
                formatDate = formatDate.replace("January", "Jan", true)
            }
            formatDate.contains("February", true) -> {
                formatDate = formatDate.replace("February", "Feb", true)
            }
            formatDate.contains("March", true) -> {
                formatDate = formatDate.replace("March", "Mar", true)
            }
            formatDate.contains("April", true) -> {
                formatDate = formatDate.replace("April", "Apr", true)
            }
            formatDate.contains("May", true) -> {
                formatDate = formatDate.replace("May", "May", true)
            }
            formatDate.contains("June", true) -> {
                formatDate = formatDate.replace("June", "Jun", true)
            }
            formatDate.contains("July", true) -> {
                formatDate = formatDate.replace("July", "Jul", true)
            }
            formatDate.contains("August", true) -> {
                formatDate = formatDate.replace("August", "Aug", true)
            }
            formatDate.contains("September", true) -> {
                formatDate = formatDate.replace("September", "Sept", true)
            }
            formatDate.contains("October", true) -> {
                formatDate = formatDate.replace("October", "Oct", true)
            }
            formatDate.contains("November", true) -> {
                formatDate = formatDate.replace("November", "Nov", true)
            }
            formatDate.contains("December", true) -> {
                formatDate = formatDate.replace("December", "Dec", true)
            }
        }
        return formatDate
    }
}